//
//  NSTimer+Addition.m
//  GreenWheelCustomer
//
//  Created by zengweihuan on 2018/8/2.
//  Copyright © 2018年 FZHD. All rights reserved.
//

#import "NSTimer+Addition.h"


@implementation NSTimer (Addition)
/// 暂停
- (void)pause {
    if (!self.isValid) return;
    [self setFireDate:[NSDate distantFuture]];
}
/// 恢复
- (void)resume {
    if (!self.isValid) return;
    [self setFireDate:[NSDate date]];
    
}
/// 多少秒后恢复
- (void)resumeWithTimeInterval:(NSTimeInterval)time {
    if (!self.isValid) return;
    [self setFireDate:[NSDate dateWithTimeIntervalSinceNow:time]];
}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                repeats:(BOOL)repeats
                               timerCallback:(NSTimerBlock)timerCallback {

    return [NSTimer scheduledTimerWithTimeInterval:interval
                                        target:self
                                      selector:@selector(onTimerUpdateBlock:)
                                      userInfo:[timerCallback copy]
                                       repeats:repeats];
}

+ (void)onTimerUpdateBlock:(NSTimer *)timer {
    NSTimerBlock block = timer.userInfo;

    if (block) {
        block();
    }
}



+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                  repeats:(BOOL)repeats
                                  limitCount:(NSInteger)limitCount
                               timerCallback:(NSTimerBlock)timerCallback {
    NSDictionary *userInfo = @{@"timerCallback"     : [timerCallback copy],
                           @"limitCount"        : @(limitCount)};

    return [NSTimer scheduledTimerWithTimeInterval:interval
                                        target:self
                                      selector:@selector(beyoudLimitTime:)
                                      userInfo:userInfo
                                       repeats:repeats];
}

+ (void)beyoudLimitTime:(NSTimer *)timer {
    static NSUInteger currentCount = 0;

    NSDictionary *userInfo = timer.userInfo;
    NSTimerBlock timerCallBack = userInfo[@"timerCallback"];
    NSNumber *count = userInfo[@"limitCount"];

    currentCount ++;

    if (currentCount > count.integerValue) {
        if (timerCallBack) {
            currentCount = 0;
            timerCallBack();
        }
    }
}
@end
